package org.example.MedicalCrowdsourcing.controller;

import org.example.MedicalCrowdsourcing.model.entity.BlockchainProject;
import org.example.MedicalCrowdsourcing.model.entity.BlockchainTransaction;
import org.example.MedicalCrowdsourcing.model.entity.LoginRecord;
import org.example.MedicalCrowdsourcing.model.entity.User;
import org.example.MedicalCrowdsourcing.repository.BlockchainProjectRepository;
import org.example.MedicalCrowdsourcing.repository.BlockchainTransactionRepository;
import org.example.MedicalCrowdsourcing.repository.LoginRecordRepository;
import org.example.MedicalCrowdsourcing.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

/**
 * 数据库查询控制器
 * 仅供管理员使用，用于验证数据库同步功能
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8081", allowCredentials = "true")
public class DatabaseController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LoginRecordRepository loginRecordRepository;

    @Autowired
    private BlockchainProjectRepository blockchainProjectRepository;

    @Autowired
    private BlockchainTransactionRepository blockchainTransactionRepository;

    /**
     * 获取所有用户列表
     */
    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers() {
        List<User> users = userRepository.findAll();
        // 移除敏感信息
        List<Map<String, Object>> sanitizedUsers = users.stream()
                .map(user -> {
                    Map<String, Object> userMap = new HashMap<>();
                    userMap.put("id", user.getId());
                    userMap.put("username", user.getUsername());
                    userMap.put("email", user.getEmail());
                    userMap.put("role", user.getRole().getName());
                    userMap.put("blockchainAddress", user.getBlockchainAddress());
                    userMap.put("createdAt", user.getCreatedAt());
                    userMap.put("lastLogin", user.getLastLogin());
                    return userMap;
                })
                .collect(Collectors.toList());
        return ResponseEntity.ok(sanitizedUsers);
    }

    /**
     * 获取所有登录记录
     */
    @GetMapping("/login-records")
    public ResponseEntity<?> getAllLoginRecords() {
        List<LoginRecord> records = loginRecordRepository.findAll();
        return ResponseEntity.ok(records);
    }

    /**
     * 获取所有区块链项目
     */
    @GetMapping("/blockchain-projects")
    public ResponseEntity<?> getAllBlockchainProjects() {
        List<BlockchainProject> projects = blockchainProjectRepository.findAll();
        return ResponseEntity.ok(projects);
    }

    /**
     * 获取特定用户的区块链项目
     */
    @GetMapping("/blockchain-projects/user/{username}")
    public ResponseEntity<?> getUserBlockchainProjects(@PathVariable String username) {
        User user = userRepository.findByUsername(username).orElse(null);
        if (user == null) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "User not found");
            return ResponseEntity.badRequest().body(response);
        }
        List<BlockchainProject> projects = blockchainProjectRepository.findByCreator(user);
        return ResponseEntity.ok(projects);
    }

    /**
     * 获取所有区块链交易
     */
    @GetMapping("/blockchain-transactions")
    public ResponseEntity<?> getAllBlockchainTransactions() {
        List<BlockchainTransaction> transactions = blockchainTransactionRepository.findAll();
        return ResponseEntity.ok(transactions);
    }

    /**
     * 获取特定项目的交易记录
     */
    @GetMapping("/blockchain-transactions/project/{projectId}")
    public ResponseEntity<?> getProjectBlockchainTransactions(@PathVariable String projectId) {
        try {
            BlockchainProject project = blockchainProjectRepository.findByBlockchainId(new BigInteger(projectId))
                    .orElse(null);
            if (project == null) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "Project not found");
                return ResponseEntity.badRequest().body(response);
            }
            List<BlockchainTransaction> transactions = blockchainTransactionRepository.findByProject(project);
            return ResponseEntity.ok(transactions);
        } catch (NumberFormatException e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "Invalid project ID format");
            return ResponseEntity.badRequest().body(response);
        }
    }
} 